package com.sky.controller.admin;

import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("员工登陆")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @ApiOperation("员工登出")
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     * @return Result
     */
    @PostMapping
    @ApiOperation("新增员工")
    public Result<String> employeeAdd(@RequestBody EmployeeDTO employeeDTO) {
        log.info("新增员工：{}", employeeDTO.getUsername());

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setStatus(StatusConstant.ENABLE);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        Result<String> result = employeeService.employeeAdd(employee);
        BaseContext.removeCurrentId();
        return result;
    }

    /**
     * 分页查询员工
     *
     * @param pageQueryDTO
     * @return Result
     */
    @ApiOperation("分页查询员工")
    @GetMapping("/page")
    public Result<PageResult> employeePageQuery(EmployeePageQueryDTO pageQueryDTO) {
        log.info("员工分页查询，参数为{}", pageQueryDTO);
        PageResult result = employeeService.employeePageQuery(pageQueryDTO);
        return Result.success(result);
    }

    /**
     * 更改员工激活状态
     *
     * @param id
     * @return Result
     */
    @ApiOperation("修改员工激活状态")
    @PostMapping("/status/{status}")
    public Result employeeStatusUpdate(@PathVariable Integer status, Long id) {
        log.info("员工{}被" + (StatusConstant.ENABLE.equals(status) ? "激活。" : "禁用。"), id);
        employeeService.employeeStatusUpdate(id, status);
        return Result.success();
    }

    /**
     * 编辑员工信息
     *
     * @param dto
     * @return Result
     */
    @ApiOperation("编辑员工信息")
    @PutMapping()
    public Result employeeEdit(@RequestBody EmployeeDTO dto) {
        log.info("开始修改员工{}", dto.getId());
        employeeService.employeeEdit(dto);
        return Result.success();
    }

    /**
     * 根据查询员工信息
     *
     * @param id
     * @return Result
     */
    @ApiOperation("查询员工信息")
    @GetMapping("/{id}")
    public Result employeeEdit(@PathVariable Long id) {
        log.info("查询员工{}", id);
        try {
            return Result.success(employeeService.getById(id));
        } catch (NullPointerException e) {
            return Result.error("id为" + id + "的员工不存在");
        }

    }
}
